package com.ruoyi.web.controller.his;

import java.util.*;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.dto.DailyBookingLimmit;
import com.ruoyi.common.dto.WeeklyScheduleData;
import com.ruoyi.common.utils.RedisCache;
import com.ruoyi.his.domain.HisTeamGroup;
import com.ruoyi.his.domain.HisWorkShift;
import com.ruoyi.his.service.IHisTeamGroupService;
import com.ruoyi.his.service.IHisWorkShiftService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.his.domain.HisSchedulePlan;
import com.ruoyi.his.service.IHisSchedulePlanService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 排班计划Controller
 *
 * @author tsenlem
 * @date 2023-11-02
 */
@Controller
@RequestMapping("/his/plan")
public class HisSchedulePlanController extends BaseController {
    private String prefix = "his/plan";

    @Autowired
    private IHisSchedulePlanService hisSchedulePlanService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IHisTeamGroupService teamGroupService;

    @Autowired
    private IHisWorkShiftService workShiftService;

    @Autowired
    private RedisCache redisCache;

    @RequiresPermissions("his:plan:view")
    @GetMapping()
    public String plan(ModelMap map) {
        List<HisTeamGroup> teams = teamGroupService.selectHisTeamGroupList("E");
        HisTeamGroup teamGroup = teams.get(0);

        map.put("teamGroup", teamGroup);

        HisWorkShift shift = new HisWorkShift();
        shift.setTid(teamGroup.getId());
        List<HisWorkShift> workShifts = workShiftService.selectHisWorkShiftList(shift);
        map.put("shifts", workShifts);

        SysUser user = new SysUser();
        user.setStatus("0");
        List<SysUser> users = userService.selectUserList(user);
        map.put("users", users);

        HisSchedulePlan plan = new HisSchedulePlan();
        plan.setTid(teamGroup.getId());
        plan.setDuty("Y");
        List<HisSchedulePlan> plans = hisSchedulePlanService.selectHisSchedulePlanList(plan);

        Map<String,Integer> planMap = new HashMap<>();
        for (HisSchedulePlan p : plans) {
            StringBuffer buffer = new StringBuffer();
            buffer.append(p.getTid())
                    .append(p.getSid())
                    .append(p.getUid())
                    .append(p.getWeekDay());
            planMap.put(buffer.toString(), 1);
        }
        map.put("planMap", planMap);

        return prefix + "/plan";
    }

    /**
     * 查询排班计划列表
     */
    @RequiresPermissions("his:plan:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(HisSchedulePlan hisSchedulePlan) {
        startPage();
        List<HisSchedulePlan> list = hisSchedulePlanService.selectHisSchedulePlanList(hisSchedulePlan);
        return getDataTable(list);
    }

    /**
     * 导出排班计划列表
     */
    @RequiresPermissions("his:plan:export")
    @Log(title = "排班计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(HisSchedulePlan hisSchedulePlan) {
        List<HisSchedulePlan> list = hisSchedulePlanService.selectHisSchedulePlanList(hisSchedulePlan);
        ExcelUtil<HisSchedulePlan> util = new ExcelUtil<HisSchedulePlan>(HisSchedulePlan.class);
        return util.exportExcel(list, "排班计划数据");
    }

    /**
     * 新增排班计划
     */
    @GetMapping("/add")
    public String add(ModelMap map) {
        List<HisTeamGroup> list = teamGroupService.selectHisTeamGroupList("E");
        HisTeamGroup teamGroup = list.get(0);

        map.put("teamGroup", teamGroup);

        HisWorkShift shift = new HisWorkShift();
        shift.setTid(teamGroup.getId());
        List<HisWorkShift> workShifts = workShiftService.selectHisWorkShiftList(shift);
        map.put("shifts", workShifts);

        SysUser user = new SysUser();
        user.setStatus("0");
        List<SysUser> users = userService.selectUserList(user);
        map.put("users", users);

        return prefix + "/add";
    }

    /**
     * 新增保存排班计划
     */
    @RequiresPermissions("his:plan:add")
    @Log(title = "排班计划", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Integer tid, String[] works) {
        Date now = new Date();

        List<HisSchedulePlan> plans = new ArrayList<>();
        for (String work : works) {
            String[] values = work.split(",");
            System.out.println(values[0]);
            HisSchedulePlan plan = new HisSchedulePlan();
            plan.setTid(1);
            plan.setSid(Integer.valueOf(values[1]));
            plan.setUid(Integer.valueOf(values[2]));
            plan.setWeekDay(Integer.valueOf(values[3]));
            plan.setDuty(values[4]);
            plan.setCreateBy(getLoginName());
            plan.setCreateTime(now);
            plans.add(plan);
        }

        Integer count = hisSchedulePlanService.insertHisSchedulePlans(plans);
        if (count > 0) {
            //每日预约人数
            List<DailyBookingLimmit> dailyBookingLimmits = hisSchedulePlanService.selectDailyBookingLimit();
            for (DailyBookingLimmit limmit : dailyBookingLimmits) {
                String duty = "doctor";
                if ("10".equals(limmit.getDuty())) {
                    duty = "therapy";
                }
                int weekDay = limmit.getWeekDay();
                StringBuffer buffer = new StringBuffer("schedule:regs:");
                String key = buffer.append(duty)
                        .append(":")
                        .append(weekDay).toString();
//                redisCache.setCacheObject(key, limmit.getCeiling());
                redisCache.setCacheObject(key, "limmit", limmit.getCeiling());
                redisCache.setCacheObject(key, "inverse", limmit.getCeiling()); //倒数 用于预约递减，当递减到0时为满号

            }

            //每周排班数据
            List<WeeklyScheduleData> weeklyScheduleDataList = hisSchedulePlanService.selectWeeklyScheduleData();
            for (WeeklyScheduleData scheduleData : weeklyScheduleDataList) {
                Map<String, Object> cacheMap = redisCache.getCacheMap("sys_user:user_id:" + scheduleData.getUserId());
                StringBuffer buffer = new StringBuffer("schedule:plan:");
                String duty = (String) cacheMap.get("duty");
                if ("10".equals(duty)) {
                    buffer.append("therapy:");
                }else{
                    buffer.append("doctor:");
                }

                String key = buffer.append(scheduleData.getWeekDay()).append(":")
                        .append(scheduleData.getUserId()).append(":")
                        .append(scheduleData.getSid()).toString();
                Map<String, Object> dataMap = new HashMap<String, Object>() {
                    {
                        put("userId", scheduleData.getUserId());
                        put("sid", scheduleData.getSid());
                        put("weekDay", scheduleData.getWeekDay());
                        put("sort", scheduleData.getSort());
                        put("label", scheduleData.getLabel());
                        put("shift", scheduleData.getShift());
                        put("limmit", scheduleData.getLimmit());
                        put("actual",0);
                    }
                };

                redisCache.setCacheMap(key,dataMap);
            }
        }

        return success("排班添加成功");
    }

    /**
     * 修改排班计划
     */
    @RequiresPermissions("his:plan:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap map) {
//        HisSchedulePlan hisSchedulePlan = hisSchedulePlanService.selectHisSchedulePlanById(id);
//        mmap.put("hisSchedulePlan", hisSchedulePlan);
        List<HisTeamGroup> list = teamGroupService.selectHisTeamGroupList("E");
        HisTeamGroup teamGroup = list.get(0);

        map.put("teamGroup", teamGroup);

        HisWorkShift shift = new HisWorkShift();
        shift.setTid(teamGroup.getId());
        List<HisWorkShift> workShifts = workShiftService.selectHisWorkShiftList(shift);
        map.put("shifts", workShifts);

        SysUser user = new SysUser();
        user.setStatus("0");
        List<SysUser> users = userService.selectUserList(user);
        map.put("users", users);

        HisSchedulePlan plan = new HisSchedulePlan();
        plan.setTid(teamGroup.getId());
        plan.setDuty("Y");
        List<HisSchedulePlan> plans = hisSchedulePlanService.selectHisSchedulePlanList(plan);

        Map<String,Integer> planMap = new HashMap<>();
        for (HisSchedulePlan p : plans) {
            StringBuffer buffer = new StringBuffer();
            buffer.append(p.getTid())
                    .append(p.getSid())
                    .append(p.getUid())
                    .append(p.getWeekDay());
            planMap.put(buffer.toString(), 1);
        }
        map.put("planMap", planMap);

        return prefix + "/edit";
    }

    /**
     * 修改保存排班计划
     */
    @RequiresPermissions("his:plan:edit")
    @Log(title = "排班计划", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Integer tid, String[] works) {
        HisSchedulePlan plan = new HisSchedulePlan();
        plan.setTid(tid);
        plan.setUpdateBy(getSysUser().getUserName());
        plan.setDuty("N");

        int count = hisSchedulePlanService.updateHisSchedulePlanByTid(plan);
        if(count > 0){
            addSave(tid, works);
            return success("排班修改成功");
        }

        return error("排班计划修改失败");
    }

    /**
     * 删除排班计划
     */
    @RequiresPermissions("his:plan:remove")
    @Log(title = "排班计划", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(hisSchedulePlanService.deleteHisSchedulePlanByIds(ids));
    }
}
